package com.bnz.service.impl;

import com.bnz.mapper.ClassesMapper;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.Student;
import com.bnz.pojo.StudentExample;
import com.bnz.service.StudentService;
import com.bnz.util.MyBatisUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassesMapper classesMapper;
    //查所有
    @Override
    public List<Student> findAll() {
        List<Student> students = studentMapper.selectByExample(null);
        //绑定班级
//        for (Student student : students) {
//            Classes classes = classesMapper.selectByPrimaryKey(student.getCid());
//            student.setCname(classes.getCname());
//        }
        return students;


    }

    /**
     * 分页
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Student> findByPage(int page, int pageSize) {
        //开始分页
        PageHelper.startPage(page,pageSize);
        //定义实例查询
        StudentExample example =new StudentExample();

        List<Student> students = studentMapper.selectByExample(example);
//        //绑定班级
//        for (Student student : students) {
//            classesMapper.
//        }
        //转换page
        Page<Student> page1 = (Page<Student>) students;
        //返回pageResult
         return new PageResult<>(page1.getTotal(),page1.getResult());
    }

    /**
     * 条件查询带分页
     * @param page
     * @param pageSize
     * @param student
     * @return
     */
    @Override
    public PageResult<Student> search(Integer page, Integer pageSize, Student student) {
        //开始分页
        PageHelper.startPage(page, pageSize);
        //定义查询实例
        StudentExample example = new StudentExample();
        //封装查询条件
        StudentExample.Criteria criteria = example.createCriteria();
        List<Student> students = null;
        if (student != null) {
            if (StringUtils.isNotBlank(student.getSname())) {
                criteria.andSnameLike("%" + student.getSname() + "%");
            }
            if (StringUtils.isNotBlank(student.getAddr())) {
                criteria.andAddrLike("%" + student.getAddr() + "%");
            }
            if (student.getCid() != null && student.getCid() != 0) {
                criteria.andCidEqualTo(student.getCid());
            }
            students = studentMapper.selectByExample(example);
        }
        //3.3 转换为
        Page<Student> studentPage = (Page<Student>) students;
        //3.4 返回PageResult
        return new PageResult<>(studentPage.getTotal(), studentPage.getResult());
    }
}
